﻿/*-----------------------------------------------------------------------
 * <copyright file="SelAnyContainer.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>zhang jun</author>
 * <summary> 
 *          SearchCtrl
 *          作成日：06/13/2010
 *                  06/28/2010 把查询稼动率类型的服务移除
 *                  07/05/2010 修改 在弹出查询子窗体的过程中,btnOPID按钮不可用
 *                  07/08/2010 修改 日期选择默认为当天和后一天 （现场）
 *                  08/11/2010 增加 数据导出功能（除了SV和QC都可以使用这个功能）
 *                  08/19/2010 修改 OPID的显示方式
 *                  10/15/2010 增加 日志中记录用户查询条件。
 * </summary>
 *-----------------------------------------------------------------------
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl
{
    using System;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFLog4Ref;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.OPQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;

    /// <summary>
    /// 查询控件 SelAnyContainer
    /// </summary>
    public partial class SelAnyContainer : UserControl
    {
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " 查询公用框SelAnyContainer ";

        /// <summary>
        /// 查询OPID的子窗体
        /// operatorIDSelChildWin
        /// </summary>
        private childWindow.OPIDSelectChildWindow operatorIDSelChildWin;

        /// <summary>
        /// 消息提示子窗体
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 日志服务定义
        /// wcfLogClient
        /// </summary>
        private WCFLog4Client wcfLogClient;

        /// <summary>
        /// 查询服务定义
        /// wcfOPWorkEfficiencyQueryClient
        /// </summary>
        private WCFOPCorrelationClient wcfOPWorkEfficiencyQueryClient;

        /// <summary>
        /// 稼动率类型
        /// statsticClass
        /// </summary>
        private string statsticClass = string.Empty;

        /// <summary>
        /// 查询命令 导出命令
        /// queryCcommand exportComand
        /// </summary>
        private Command.ICommand queryCcommand = null, exportComand = null;

        /// <summary>
        /// 记录用户查询条件
        /// </summary>
        /// <value>10/15/2010 Add</value>
        public string WhereIntorLogs
        {
            get;
            set;
        }

        /// <summary>
        /// 构造函数 SelAnyContainer
        /// </summary>
        public SelAnyContainer()
        {
            InitializeComponent();

            this.InitField();

            // 引用主题
            ((App)Application.Current).SetTheme(LayoutRoot);
            //Accordion 时的Border 控件 引用主题
            ((App)Application.Current).SetTheme(bAccordionItemBorder);


            // OPID按钮单击事件
            this.btnOPID.Click += new RoutedEventHandler(this.BtnOPID_Click);

            // 查询按钮
            this.btnSelect.Click += new RoutedEventHandler(this.BtnSelect_Click);

            // 开始日期(DatePicker)
            this.dpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(this.DpDateFrom_SelectedDateChanged);

            // 结束日期(DatePicker)
            this.dpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(this.DpDateTo_SelectedDateChanged);

            // 查询OPID的子窗体关闭
            this.operatorIDSelChildWin.Closed += new EventHandler(this.OpIDSelChildWin_Closed);

            this.btnExport.Click += new RoutedEventHandler(this.BtnExport_Click);

            //设置 查询界面 的 查询按钮 数据导出 初始化可用
            this.btnSelect.IsEnabled = true;
            this.btnExport.IsEnabled = true;

            // btnOPID按钮  可用
            this.btnOPID.IsEnabled = true;

            this.dpDateFrom.SelectedDate = DateTime.Now.AddDays(-1);

            this.dpDateTo.SelectedDate = DateTime.Now.Date;

            // 如果不是 SV或QC，显示导出按钮
            if (!(FunctionClass.GetUserIdentity() == FunctionClass.UserIdentity.SV.ToString() ||
                    FunctionClass.GetUserIdentity() == FunctionClass.UserIdentity.QC.ToString()))
            {
                this.btnExport.Visibility = Visibility.Visible;
            }
            else
            {
                this.btnExport.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Gets or sets value of exportComand
        /// </summary>
        public Command.ICommand ExportComand
        {
            get { return this.exportComand; }
            set { this.exportComand = value; }
        }

        /// <summary>
        /// Gets or sets value of queryCcommand
        /// </summary>
        public Command.ICommand QueryCcommand
        {
            get { return this.queryCcommand; }
            set { this.queryCcommand = value; }
        }

        /// <summary>
        /// 变量初始化方法  InitField
        /// </summary>
        private void InitField()
        {
            this.operatorIDSelChildWin = new childWindow.OPIDSelectChildWindow();
            this.wcfLogClient = Wcf.Service.Log4;
            this.errorMessbox = new childWindow.MessageBox();
            this.wcfOPWorkEfficiencyQueryClient = Wcf.Service.OPWorkEfficiencyQuery;
        }       

        /// <summary>
        /// 查询按钮点击事件
        /// BtnSelect_Click
        /// </summary>
        /// <param name="sender">Sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnSelect_Click(object sender, RoutedEventArgs e)
        {
            writeWhereLog();
            this.btnSelect.IsEnabled = false;
      
            this.QueryCcommand.Exec();
           
        }

        /// <summary>
        /// 导出按钮点击事件
        /// BtnExport_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            writeWhereLog();
            this.btnExport.IsEnabled = false;

            this.exportComand.Exec();
        }

        #region 初始化 稼动率 COMBMBOX 无效
        ///// <summary>
        ///// 初始化 稼动率 COMBMBOX
        ///// </summary>
        ///// <param name="sender">sender of object</param>
        ///// <param name="e">e type of SelectStatsticClassCompletedEventArgs</param>
        //private void WCFOPWorkEfficiencyQueryClient_SelectStatsticClassCompleted(object sender, SelectStatsticClassCompletedEventArgs e)
        //{ 
        //    try
        //    {
        //        if (e.Error == null)
        //        {
        //            if (e.Result.Count > 0)
        //            {
        //                if (this.cbWorkEfficiency.ItemsSource != null)
        //                {
        //                    this.cbWorkEfficiency.ItemsSource = null;
        //                }

        //                List<string> comlist = (from com in e.Result
        //                                        select com.StatsticClass).ToList<string>();

        //                this.cbWorkEfficiency.ItemsSource = comlist;
        //                this.cbWorkEfficiency.SelectedIndex = 1;
        //            }
        //            else
        //            {
        //                this.cbWorkEfficiency.DataContext = null;
        //                throw (new Exception("COMBMBOX初始化失败"));
        //            }
        //        }
        //        else
        //        {
        //            throw (new Exception("WCFOPWrokEfficiencyQueryRef服务返回值有错" + e.Error.Message.ToString()));
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "用户 " + ClientUserInfor.UserRealName + " OPWorkEfficiencyQuery " + ex.Message.ToString());
        //        FunctionClass.ShowMessageBox(
        //          this.errorMessbox,
        //           "提示",
        //           ex.Message.ToString(),
        //           Colors.Gray,
        //           true,
        //           Colors.Red,
        //           Visibility.Visible,
        //           Visibility.Collapsed);
        //        return;
        //    }
        //}

        #endregion 初始化 稼动率 COMBMBOX 无效

        #region 查询子窗体相关

        /// <summary>
        /// 弹出查询子窗体(...按钮)
        /// 当单击按钮时，弹出CommonWin\OPIDSelectChildWindow
        /// 子窗口
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void BtnOPID_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserName))
            {

                if (!String.IsNullOrEmpty(this.tbOPID.Text))
                {
                    this.tbOPID.Text = string.Empty;
                }

                this.operatorIDSelChildWin.Title = "查询子窗体";
                this.operatorIDSelChildWin.Show();
                this.btnOPID.IsEnabled = false;
            }
            else
            {
                Common.FunctionList.FunctionClass.ShowMessageBox(
                  this.errorMessbox,
                  1,
                  "提示",
                  "当前用户信息有误。",
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 查询OPID的子窗体关闭(实现)
        /// OpIDSelChildWin_Closed
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void OpIDSelChildWin_Closed(object sender, EventArgs e)
        {
            try
            {
                this.btnOPID.IsEnabled = true;
                tbOPID.Text = string.Empty;
                tbOPID.Tag = string.Empty;

                this.operatorIDSelChildWin = sender as Common.Window.OPIDSelectChildWindow;

                // 08/19/2010 -- 修改 OPID的显示方式
                if (this.operatorIDSelChildWin.DialogResult == true)
                {
                    /* 选择部分OP
                     * TextBox上显示的是所选的OP的ID号
                     * 添加逗号
                     * ClientDataList.SelOpIDList的单引号，已经删除
                     */
                    if (ClientDataList.SelOpIDList.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in ClientDataList.SelOpIDList)
                        {
                            // --30/05/2010--修改
                            sb.Append(str + ",");
                        }

                        // 去除尾部多余逗号
                        this.tbOPID.Text = sb.ToString().Remove(sb.ToString().Length - 1, 1);
                        ClientDataList.SelOpIDList.Clear();
                        return;
                    }

                    /* 选择所有OP和选择组
                    * ClientDataList.CheckOpUnitList一旦有值，不能清空
                    * TextBox.Text上显示的是对应选择值
                    * TextBox.Tag 的值是后台判断的条件
                    */
                    if (ClientDataList.CheckOpUnitList.Count > 0)
                    {
                        tbOPID.Tag = "ALL";

                        //选择所有OP
                        if (this.operatorIDSelChildWin.SelectStatus.ToUpper().Contains("OPERATORS"))
                        {
                            tbOPID.Text = this.operatorIDSelChildWin.SelectStatus;
                        }

                        //选择组
                        if (this.operatorIDSelChildWin.SelectStatus.ToUpper().Contains("UNIT"))
                        {
                            StringBuilder sbUnit = new StringBuilder();
                            foreach (string unitName in ClientDataList.CheckOpUnitList)
                            {
                                sbUnit.Append(unitName);
                                sbUnit.Append("Unit");
                                sbUnit.Append(" ");
                            }
                            tbOPID.Text = sbUnit.ToString();
                        }
                        return;
                    }
                }

                if (this.operatorIDSelChildWin.DialogResult == false)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName+" 转换OPID时出错" + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                               this.errorMessbox,
                               1,
                               "提示",
                               ex.Message.ToString(),
                               Colors.Gray,
                               true,
                               Visibility.Visible,
                               Visibility.Collapsed);
                return;
            }
        }
        #endregion 查询子窗体相关 

        #region 日期(DatePicker)
        /// <summary>
        /// 结束日期(DatePicker)
        /// DpDateTo_SelectedDateChanged
        /// </summary>
        /// <param name="sender">sender of obejct</param>
        /// <param name="e">e type of SelectionChangedEventArgs</param>
        private void DpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dpDateTo == null || dpDateTo.SelectedDate == null)
            {
                return;
            }
            else
            {
                this.dpDateTo.Text = this.dpDateTo.SelectedDate.Value.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 开始日期(DatePicker)
        /// 防止选错时，出现BUG
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectionChangedEventArgs</param>
        private void DpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dpDateFrom == null || dpDateFrom.SelectedDate == null)
            {
                return;
            }
            else
            {
                this.dpDateFrom.Text = this.dpDateFrom.SelectedDate.Value.ToString("yyyy-MM-dd");
            }
        }
        #endregion 日期(DatePicker)

        #region 记录用户选择的WHERE条件
        /// <summary>
        /// 记录用户选择的WHERE条件
        /// </summary>
        /// <returns></returns>
        /// <value>10/15/2010 Add </value>
        private void writeWhereLog()
        {
            StringBuilder sbWhereIntorLogs = new StringBuilder();
            try
            {
                //日志用
                sbWhereIntorLogs.Append(" 查询条件：");
                sbWhereIntorLogs.Append(" 开始日期：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.dpDateFrom.Text) == true ? " null" : this.dpDateFrom.Text);
                sbWhereIntorLogs.Append(" 结束日期：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.dpDateTo.Text) == true ? " null" : this.dpDateTo.Text);
                sbWhereIntorLogs.Append(" 稼动率类别：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.cbWorkEfficiency.SelectionBoxItem.ToString()) == true ? " null" : this.cbWorkEfficiency.SelectionBoxItem.ToString());
                sbWhereIntorLogs.Append(" OP信息：");
                sbWhereIntorLogs.Append(string.IsNullOrEmpty(this.tbOPID.Text) == true ? " null" : this.tbOPID.Text);
            }
            catch
            {
                WhereIntorLogs = string.Empty;
            }

            WhereIntorLogs = sbWhereIntorLogs.ToString();
        }

        #endregion 记录用户选择的WHERE条件

    }
}
